package cn.iocoder.yudao.module.ym.controller.admin.site;

import cn.hutool.core.lang.Pair;
import cn.iocoder.yudao.module.infra.listener.ErrorContinuingReadListener;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.connection.ConnectionDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.site.SiteDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.sitedata.SiteDataDO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.*;

import cn.iocoder.yudao.module.ym.controller.admin.site.vo.*;
import cn.iocoder.yudao.module.ym.service.site.SiteService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 电站")
@RestController
@RequestMapping("/ym/site")
@Validated
public class SiteController {

    @Resource
    private SiteService siteService;

    private List<String> errors;

    @PostMapping("/create")
    @Operation(summary = "创建电站")
    public CommonResult<Long> createSite(@Valid @RequestBody SiteSaveReqVO createReqVO) {
        return success(siteService.createSite(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新电站")
    public CommonResult<Boolean> updateSite(@Valid @RequestBody SiteSaveReqVO updateReqVO) {
        siteService.updateSite(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除电站")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteSite(@RequestParam("id") Long id) {
        siteService.deleteSite(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得电站")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<SiteRespVO> getSite(@RequestParam("id") Long id) {
        return success(siteService.getSite(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得电站分页")
    public CommonResult<PageResult<SiteRespVO>> getSitePage(@Valid SitePageReqVO pageReqVO) {
        return success(siteService.getSitePage(pageReqVO));
    }

    @GetMapping("/list")
    @Operation(summary = "获得电站分页")
    public CommonResult<List<SimpleSiteRespVO>> getSimpleSiteList(@Valid SitePageReqVO pageReqVO) {
        return success(siteService.getSimpleSiteList(pageReqVO));
    }

    @GetMapping("/getSiteByAreaId")
    @Operation(summary = "区域获得电站不分页")
    public CommonResult<List<SiteRespVO>> getSiteByAreaId(Long areaId,Long userId) {
        return success(siteService.getSiteByAreaId(areaId,userId));
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出电站 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSiteExcel(@Valid SitePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        // 导出 Excel
        ExcelUtils.write(response, "电站.xls", "电站数据", SiteRespVO.class,
                siteService.getSitePage(pageReqVO).getList());
    }

   /* @PostMapping("/excel-import")
    public CommonResult<UserImportRespVO> uploadExcel(@RequestParam("file") MultipartFile file, Boolean updateSupport) {
        // 2. 解析Excel数据
        List<Map<String, Object>> dataList = ExcelUtils.excelToMap(file);
        return success(siteService.importSite(dataList,updateSupport));

    }*/

    @PostMapping("/excel-import")
    public CommonResult<UserImportRespVO> uploadExcel(@RequestParam("file") MultipartFile file, Boolean updateSupport) throws IOException {
        ErrorContinuingReadListener<SiteImportVO> listener = new ErrorContinuingReadListener<>();
        // 2. 解析Excel数据

        EasyExcel.read(file.getInputStream(), SiteImportVO.class, listener)
                .autoCloseStream(true)
                .sheet()// 不要自动关闭，交给 Servlet 自己处理
                .doRead();
        List<String> errors = listener.getErrors();


        if (!CollectionUtils.isEmpty(errors)) {

            return error1(errors); // 返回带错误信息的响应
        }else {
            List<SiteImportVO> read = EasyExcel.read(file.getInputStream(), SiteImportVO.class, null)
                    .autoCloseStream(false)
                    .sheet()// 不要自动关闭，交给 Servlet 自己处理
                    .doReadSync();

            return success(siteService.importSite(read,updateSupport));
        }


    }

    @PostMapping("/planningArea")
    @Operation(summary = "自动匹配")
    public CommonResult<Pair<List<SiteBindingVO>, List<ConnectionDO>>> planningArea() {
        return success(siteService.planningArea());
    }

    @PostMapping("/confirmPlanningArea")
    @Operation(summary = "确认匹配内容")
    public CommonResult<Boolean> confirmPlanningArea(@RequestBody SiteBindingVO siteBindingVO) {
        List<SiteBindingVO> siteBindingVOList = siteBindingVO.getSiteBindingVOList();
        List<ConnectionDO> connectionDOList = siteBindingVO.getConnectionDOList();
        siteService.confirmPlanningArea(siteBindingVOList,connectionDOList);
        String s = "电站自动匹配完成";
        return success(true,s);
    }



    @PostMapping("/siteInScreen")
    @Operation(summary = "获取在屏幕内的站点信息")
    public CommonResult<List<SimpleSiteRespVO>> siteInScreen(@RequestBody String area){
        return success(siteService.siteInScreen(area));
    }



    @GetMapping("/getSiteRoleUser")
    @Operation(summary = "获得当前电站下的所有用户对应角色的用户")
    public CommonResult<List<AdminUserDO>> getSiteRoleUser(@RequestParam("siteIds") List<Long> siteIds, @RequestParam("type")Integer type) {
        return success(siteService.getSiteRoleUser(siteIds,type));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得电站导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<SiteImportVO> list = Arrays.asList(
                SiteImportVO.builder()
                        .areaName("南海区")
                        .siteName("南海桂城天安数码站")
                        .location("广东省佛山市南海区桂城街道天安数码城三期B座新能源停车场")
                        .latitudeLongitude("[113.914567, 34.765593]")
                        .operationPlatform(1)
                        .deviceBrand(1)
                        .deviceType(1)
                        .fastNum("6")
                        .slowNum("8")
                        .adminName("张三")
                        .adminPhone("13222222222")
                        .siteStatus(5)
                        .supportingFacilities("便利店|休息室")
                        .operationType(1)
                        .electricityBill("0.9000")
                        .serviceFee("0.2000")
                        .onlineDate(LocalDateTime.now())
                        .investmentAmt("850000")
                        .totalPower("480")
                        .shareRent("800")
                        .expirationDate(LocalDateTime.now())
                        .clientName("李四")
                        .leaderName("王五")
                        .leaderPhone("13233333333")
                        .businessCategory(1)
                        .siteType(1)
                        .build());
        // 输出
        ExcelUtils.write(response, "电站导入模板.xls", "电站导入模板", SiteImportVO.class, list);
    }

}
